#include "Character.h"

const char Character::className[] = "Character";

#define method(class, name) {#name, &class::name}

Lunar<Character>::RegType Character::methods[] = {
	method(Character, load),
};

Character::Character(lua_State* L) {
	m_sfilename = "../data/script/";

	int nbArgs = lua_gettop(L);
	if (nbArgs == 1 && lua_isstring(L,1)) {
		m_sfilename += lua_tostring(L,1);
	}
	else {
		std::cerr << "Character constructor : wrong parameters" << std::endl;
		return;
	}

	// Lua initialisation
	m_pscript = lua_open();
	// Load Lua standard libraries
	luaL_openlibs(m_pscript);

	// Register class for Lua
	Lunar<Character>::Register(m_pscript);
	Lunar<Brain>::Register(m_pscript);
	Lunar<Dialog>::Register(m_pscript);

	// Launch Lua script
	if (luaL_dofile(m_pscript,m_sfilename.c_str())!=0) {
		std::cerr << lua_tostring(m_pscript,-1) << std::endl;
		exit(0);
	}

	m_pbrain = new Brain(m_pscript);
	m_pbrain->init();
}

Character::~Character() {
	delete m_pbrain;
}

void Character::update() {
	osg::Vec3d new_pos = m_pbrain->updatePosition(m_ptransform->getPosition());
	m_ptransform->setPosition(new_pos);

	osg::Quat new_att = m_pbrain->updateAttitude(m_ptransform->getAttitude());
	m_ptransform->setAttitude(new_att);
}

int Character::load(lua_State* L) {
	// Read character position
	float x,y,z;
	std::string modelFile = "../data/mesh/";

	int nbArgs = lua_gettop(L);
	if (nbArgs == 4 && lua_isnumber(L,1) && lua_isnumber(L,2) && lua_isnumber(L,3) && lua_isstring(L,4)) {
		x = lua_tonumber(L,1);
		y = lua_tonumber(L,2);
		z = lua_tonumber(L,3);
		modelFile += lua_tostring(L,4);
	}
	else {
		std::cerr << "Character loading : wrong parameters" << std::endl;
	}

	// Load character model
	m_ptransform = new osg::PositionAttitudeTransform;
	osg::Node* npc = osgDB::readNodeFile(modelFile);

	m_ptransform->addChild(npc);
	m_ptransform->setPosition(osg::Vec3(x, y, z));

	StageManager::getInstance().getRootNode()->addChild(m_ptransform);

	return 0;
}
